/* $RCSFile: EndCheckOut.aspx.cs $
 * Apache license v2 2011 by Christian Surieux
 * $Source: ?/AddonNice.ECommerce/Secure2/EndCheckOut.aspx.cs $
 * $log$
 * Revision 21 2010/08/09 11:08:12  christian.surieux
 *   Added Log comment to all .ascx .aspx .master files
 * Revision 8 2010/08/09 10:07:05  christian.surieux
 *   Added Log comment to all cs files
 */

using System;
using System.Diagnostics;
using System.Collections;
using System.Collections.Specialized;
using System.ComponentModel;
using System.Data;
using System.IO;
using System.Data.SqlClient;
using System.Drawing;
using System.Web;
using System.Web.SessionState;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.HtmlControls;
using System.Web.Mail;
using System.Configuration;
using System.Xml;
using System.Globalization;

using AddonNice.Security;
using AddonNice.Configuration;
using AddonNice.UI;
using AddonNice.ECommerce.UI.WebControls;
using AddonNice.Core;
using AddonNice.Helpers;
using AddonNice.Diagnostics;
using AddonNice.ECommerce.Gateways.Payment;
using AddonNice.Settings.ECommerce;

using Trace2    =   System.Diagnostics.Trace;

namespace AddonNice.ECommerce
{
	/// <summary>
	/// Summary description for Products2CheckOut.
	/// </summary>
	public partial class EndCheckOut : StdAuxPage 
	{
        public override bool HasGoogleTranslator
        {
            get
            {
                return false;
            }
        }

        public EndCheckOut ()
        {
            DefaultUrlReferrerToPageID = false;
        }

        string PaymentInstructions
        {
            get
            {
                string strcult      =   LocalizeHelper.GetCurrentNeutralCultureName();
                string wPath		=	string.Format("{0}\\Design\\ECommerceTemplates\\PaymentInstructions_{1}.html",AddonNice.Settings.Path.ApplicationPhysicalPath,strcult);
                TextReader rd       =    null;
                string beforeStr    =   string.Empty;
                try
                {
                    // Try to read directories from public theme path
                    bool exist      =   File.Exists(wPath);
                    if ( SecureTraceSwitch.Sw.TraceVerbose )
                        Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]EndCheckOut PaymentInstructions GET wPath: {0}, exists: {1}", wPath,exist ),SecureTraceSwitch.Sw.Info);
                    if ( exist)
                    {
                        rd                      =   new StreamReader(wPath);
                        beforeStr               =   rd.ReadToEnd();
                        //beforeStr               =   Server.HtmlEncode(beforeStr);
                        if ( SecureTraceSwitch.Sw.TraceVerbose )
                            Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]EndCheckOut PaymentInstructions GET file read: {0}", beforeStr.Length),SecureTraceSwitch.Sw.Info);
                    }
                    else
                    {
                        beforeStr    =   LocalizeHelper.Localize(EComStStr.ResourceFile,EComStStr.ResourceItem,"CHECKOUT_PAYMENT_INFO_10","")+"<br />";
				        beforeStr    +=   LocalizeHelper.Localize(EComStStr.ResourceFile,EComStStr.ResourceItem,"CHECKOUT_PAYMENT_INFO_12","")+"<br />";
				        beforeStr    +=   LocalizeHelper.Localize(EComStStr.ResourceFile,EComStStr.ResourceItem,"CHECKOUT_PAYMENT_INFO_13","")+"<br />";
				        beforeStr    +=   LocalizeHelper.Localize(EComStStr.ResourceFile,EComStStr.ResourceItem,"CHECKOUT_PAYMENT_INFO_14","")+"<br />";
                    }
                }
                catch (Exception ex)
                {
                    if ( SecureTraceSwitch.Sw.TraceError )
                        Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[E]EndCheckOut PaymentInstructions GET failed ex: {0}", ex),SecureTraceSwitch.Sw.Info);
                }
                finally
                {
                    if (rd != null)
                        rd.Close();
			    }
                if ( SecureTraceSwitch.Sw.TraceVerbose)
                    Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]EndCheckOut PaymentInstructions GET: {0}", beforeStr),SecureTraceSwitch.Sw.Info);
                return beforeStr;
            }
        }
	
		protected void Page_Load(object sender, System.EventArgs e)
		{
            if ( SecureTraceSwitch.Sw.TraceVerbose )
			    Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]EndCheckOut Page_Load BEG IsPostBack: {0}",IsPostBack),SecureTraceSwitch.Sw.Info);
			Response.Cache.SetCacheability(HttpCacheability.NoCache);
			if ( !IsPostBack ) 
            {
                BeforeInstructions.Controls.Add(new LiteralControl(PaymentInstructions));
				ProcessOrder();
            }
            if ( SecureTraceSwitch.Sw.TraceVerbose )
			    Trace2.WriteLine("[V]EndCheckOut Page_Load END.",SecureTraceSwitch.Sw.Info);
		}

		#region Process Payment
		private void ProcessOrder()  
		{
			// Create new order object
			Order2 o					    =	new Order2();
			// and display the form to collect payment information
			try
			{
				Guid OrderID				=	new Guid(Request.QueryString["OrderID"]);
				o.Load(OrderID);
				//Create Shipping ShopperData Object

                Hashtable Cust				=	new Hashtable();
				ShopperData sd				=	o.ShippingData;
				Cust["FirstName"]			=	sd.FirstName;
				Cust["LastName"]			=	sd.FullName;
				Cust["Company"]				=	sd.Company;
				Cust["Address1"]			=	sd.Address1;
				Cust["Address2"]			=	sd.Address2;
				Cust["Address3"]			=	sd.Address3;
				Cust["City"]				=	sd.City;
				Cust["Zip"]					=	sd.ZipCode;
				Cust["DayPhoneA"]			=	sd.Phone;
				Cust["Country"]				=	sd.Country;
				Cust["State"]				=	sd.State;
				Cust["StateID"]				=	sd.StateID;
				Cust["EMail"]				=	sd.EMail;
				Cust["Fax"]					=	sd.Fax;
				Cust["Note"]				=	sd.Note;

				// Get a reference to specified gateway and load data for specified merchant in it
                if ( OrderTrace.Sw.TraceVerbose )
                    Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]EndCheckOut ProcessOrder order: {0}, PaymentID: {1}",o, o.PaymentID),OrderTrace.Sw.Info);
                GtwPaymentProviderData dGw  =   new GtwPaymentProviderData();
                dGw.GetProvider(o.PaymentProviderID);
                // We prepare the page for going to the secure payment site 
                Guid MerchantID             =   dGw.MerchantID;
                PaymentGtwBase gateway      =   new PaymentGtwManager().GetGatewayWithData(dGw);
                gateway.MerchantID          =   MerchantID;

                // Initialize Gateway from environment
                gateway.OrderID             =   o.OrderID;
                gateway.TransacID           =   o.TransacID;
                gateway.UserID              =   o.CustomerID;
                gateway.ISOCurrencySymbol   =   o.ISOCurrencySymbol;
                gateway.Price               =   o.TotalGoods.Amount;
                gateway.Taxes               =   o.TotalTaxes.Amount;
                gateway.ShippingPrice       =   o.TotalShipping.Amount;
                gateway.Expenses            =   o.TotalExpenses.Amount;
                gateway.Discount            =   o.TotalDiscount.Amount;
                gateway.MerchantEmail       =   dGw.MerchantEmail;
                gateway.MerchantCountry     =   portalSettings.CustomSettings[EComStStr.SiteSettingsSellingCountry].ToString().ToLower();
                gateway.SubmitButtonText    =   LocalizeHelper.Localize(EComStStr.ResourceFile,EComStStr.ResourceItem,EComStStr.SubmitButtonText,"Proceed with payment");
                if (!gateway.GetForm(CheckOutprocessor1, Cust))
                {
                    string str  =   string.Format("[E]EndCheckOut ProcessOrder Error in GetForm OrderID: {0}",o.OrderID);
                    if ( SecureTraceSwitch.Sw.TraceError )
                        Trace2.WriteLine(str,SecureTraceSwitch.Sw.Info);
                    throw new Exception(str);
                }
                // keep rawTransac in db for security purpose
				try
				{
					new PaymentsDB().InsertSentTransac(o.TransacID,o.OrderID,MerchantID,DateTime.UtcNow,gateway.RawTransac);
				}
				catch(Exception ex)
				{
					// we don't crash, only SentTransac is lost. Should we ?
                    if ( SecureTraceSwitch.Sw.TraceError )
                        Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[E]EndCheckOut ProcessOrder Inserting Transac ex: {0},\r\nRawTransac: {1}",
                            ex,gateway.RawTransac),SecureTraceSwitch.Sw.Info);
				}
				GatewayForm.Visible			=	true;
                try
                {
                    OrderSummary.Text       =   o.OrderHtml;
                }
				catch(Exception ex)
				{
					// we don't crash, only SentTransac is lost. Should we ?
                    if ( SecureTraceSwitch.Sw.TraceError )
                        Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[E]EndCheckOut ProcessOrder Writing order Summary ex: {0}.",ex),SecureTraceSwitch.Sw.Info);
				}
			}
			catch(Exception exp)
			{
                if ( SecureTraceSwitch.Sw.TraceError )
				    Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[E]EndCheckOut ProcessOrder ex: {0}",exp),SecureTraceSwitch.Sw.Info);
				GatewayForm.Visible			=	false;
				try
				{
					o.Status					=	OrderStatus.Failed;
					o.Update(null);
				}
				catch(Exception ex)
				{
                    if ( SecureTraceSwitch.Sw.TraceError )
	    				Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[E]EndCheckOut ProcessOrder update status after exception failed ex: {0}",ex),SecureTraceSwitch.Sw.Info);
				}
				ExitCheckOut();
			}
		}

		#endregion

        /// <summary>
        /// to check with stdaux CancelBtn_Click
        /// </summary>
        void CancelBtn_Click(object sender, ImageClickEventArgs e)
        {
			try
			{
				Order2 o					=	new Order2();
				Guid OrderID				=	new Guid(Request.QueryString["OrderID"]);
                if ( SecureTraceSwitch.Sw.TraceVerbose )
			        Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]EndCheckOut CancelBtn_Click OrderId: {0}",OrderID),SecureTraceSwitch.Sw.Info);
				o.Load(OrderID);
				o.Status					=	OrderStatus.Failed;
				o.Update(null);
			}
			catch(Exception ex)
			{
                if ( SecureTraceSwitch.Sw.TraceError )
				    Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[E]EndCheckOut CancelBtn_Click update status ex: {0}",ex),SecureTraceSwitch.Sw.Info);
			}
			ExitCheckOut();
		}

        /// <summary>
        /// Redirects to an encheckout page adapted to payment gateway
        /// </summary>
		private void ExitCheckOut()
		{
			// stay in the secure area, confirm leaving secure site
			string EndTransacPath			=	portalSettings.CustomSettings[EComStStr.EndTransacUrl].Value;
			string ErrUrl                   =   string.Format("{0}/ko.aspx?Mid={1}&pageid={2}",EndTransacPath,ModuleID,PageID);
            if ( SecureTraceSwitch.Sw.TraceVerbose )
			    Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]EndCheckOut ExitCheckOut ErrUrl: {0}",ErrUrl),SecureTraceSwitch.Sw.Info);
			Response.Redirect(ErrUrl,true);
			//Redirect(ErrUrl,true);
		}

		#region Std overrides

        /// <summary>
        /// Buttons localization
        /// </summary>
        protected override void OnPreInit(EventArgs e)
        {
            MasterPage myMaster         =   Master;
            string strcult              =   LocalizeHelper.GetCurrentNeutralCultureName();
            CancelBtn.SkinID            =   "cancel_" + strcult;
            base.OnPreInit(e);
        }

        override protected void OnInit(EventArgs e)
		{
			InitializeComponent();
			base.OnInit(e);
		}
		
		private void InitializeComponent()
		{    
            if ( SecureTraceSwitch.Sw.TraceVerbose )
			    Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]EndCheckOut InitializeComponent ID: '{0}'",ID.ToString()),SecureTraceSwitch.Sw.Info);
			//ID                      =   "EndCheckOut";
            Load                    +=  new EventHandler(Page_Load);
            CancelBtn.Click         +=  new ImageClickEventHandler(CancelBtn_Click);
		}
		#endregion

	}
}